import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:mime/mime.dart';
import '../services/auth_service.dart';
import '../services/database_service.dart';
import '../services/minio_service.dart';
import '../models/file_item.dart';

class UploadButton extends StatefulWidget {
  final String? currentPath;
  final VoidCallback onUploadComplete;

  const UploadButton({
    Key? key,
    required this.currentPath,
    required this.onUploadComplete,
  }) : super(key: key);

  @override
  State<UploadButton> createState() => _UploadButtonState();
}

class _UploadButtonState extends State<UploadButton> {
  bool _isUploading = false;
  double _uploadProgress = 0.0;

  Future<void> _pickAndUploadFiles() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: FileType.any,
      );

      if (result != null && result.files.isNotEmpty) {
        setState(() {
          _isUploading = true;
          _uploadProgress = 0.0;
        });

        final authService = Provider.of<AuthService>(context, listen: false);
        final databaseService = Provider.of<DatabaseService>(context, listen: false);
        final minioService = Provider.of<MinioService>(context, listen: false);

        final userId = authService.currentUser!.id!;
        final totalFiles = result.files.length;

        for (int i = 0; i < result.files.length; i++) {
          final platformFile = result.files[i];
          
          if (platformFile.path != null) {
            final file = File(platformFile.path!);
            final fileName = platformFile.name;
            final fileSize = platformFile.size;
            final mimeType = lookupMimeType(fileName) ?? 'application/octet-stream';

            // Generate unique object name
            final timestamp = DateTime.now().millisecondsSinceEpoch;
            final objectName = '${timestamp}_$fileName';
            
            try {
              // Upload to MinIO
              final minioObjectName = await minioService.uploadFile(
                file,
                objectName,
                userId,
              );

              // Save to database
              final filePath = widget.currentPath != null 
                ? '${widget.currentPath}/$fileName' 
                : fileName;

              final fileItem = FileItem(
                name: fileName,
                path: filePath,
                minioObjectName: minioObjectName,
                size: fileSize,
                mimeType: mimeType,
                userId: userId,
                uploadedAt: DateTime.now(),
                parentPath: widget.currentPath,
              );

              await databaseService.insertFile(fileItem);

              // Update progress
              setState(() {
                _uploadProgress = (i + 1) / totalFiles;
              });
            } catch (e) {
              debugPrint('Error uploading file $fileName: $e');
              if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('上传文件 "$fileName" 失败: $e')),
                );
              }
            }
          }
        }

        setState(() => _isUploading = false);
        widget.onUploadComplete();

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('成功上传 $totalFiles 个文件')),
          );
        }
      }
    } catch (e) {
      setState(() => _isUploading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择文件失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isUploading) {
      return FloatingActionButton.extended(
        onPressed: null,
        icon: SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            value: _uploadProgress,
            strokeWidth: 2,
            valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
        label: Text('${(_uploadProgress * 100).toInt()}%'),
      );
    }

    return FloatingActionButton.extended(
      onPressed: _pickAndUploadFiles,
      icon: const Icon(Icons.cloud_upload),
      label: const Text('上传文件'),
    );
  }
}